package com.zjkj.mp.utils.security;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.zjkj.mp.dao.user.UserDao;
import com.zjkj.mp.vo.MpAuthority;
import com.zjkj.mp.vo.user.MpUser;
import com.zjkj.mp.vo.user.UserRoles;

/**
 * 
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数
 *
 * @author 陈晨
 * @history
 * <TABLE id="HistoryTable" border="1">
 * 	<TR><TD>时间</TD><TD>描述</TD><TD>作者</TD></TR>
 *	<TR><TD>2013-6-6</TD><TD>创建初始版本</TD><TD>陈晨</TD></TR>
 * </TABLE>
 */
public class MpUserDetailsService implements UserDetailsService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource(name="userDaoImpl")
	UserDao userDao;

	/**
	 * 获取用户Detail信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException, DataAccessException {
		MpUser user = null;
		user = userDao.getMpUserByEmail(username);
		if(null==user || "".equals(user)){
			throw new UsernameNotFoundException("用户“" + username + "”不存在");
		}
		// add end
		List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();
		try {
		
			//登录的权限
			MpAuthority ma = new MpAuthority();
			ma.setQxdm("ZH_LOGIN"); 	
			
			//根据用户的不同角色分配不同的权限
			MpAuthority role = new MpAuthority();
			if(user.getRoleID() == UserRoles.ADMIN){
				role.setQxdm("ZH_ADMIN");
			}else{
				//普通用户
				role.setQxdm("ZH_COMMON");
			}
			
			List<MpAuthority> list = new ArrayList<MpAuthority>();
			list.add(ma);
			list.add(role);
			authorityList.addAll(list);
		}
		// 20120510 add by niew
		catch (Exception g) {
			logger.error(g.toString());
			throw new UsernameNotFoundException("系统异常请稍后再试");
		}
		// add end
		logger.debug("用户：{},权限列表：{}", user.getUsername(), authorityList);
		if (authorityList == null || authorityList.size() == 0) {
			throw new UsernameNotFoundException("用户“" + username
					+ "”没有权限，请管理员分配权限");
		}
		user.setAuthorities(authorityList);
		return user;
	}
	
}

/**
 * Copyright © 2013,指尖科技 All rights reserved.
 */
